package com.tarena.lbs.basic.web.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.tarena.lbs.basic.web.service.IEsService;
import com.tarena.lbs.pojo.basic.dos.StoreDO;
import com.tarena.lbs.pojo.basic.param.EsUpdateParam;
import com.tarena.lbs.pojo.basic.query.EsQuery;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EsServiceImpl<T> implements IEsService<T> {

    @Autowired
    private EsClientUtils esClientUtils;

    @Override
    public Boolean insertData(EsUpdateParam dto, T data) {
        return esClientUtils.insertData(dto, JSONObject.toJSONString(data));
    }

    @Override
    public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder) throws Exception {
        return esClientUtils.search(indexName, searchSourceBuilder);
    }

    //查询附件5KM的数据排序
    @Override
    public SearchResponse searchGeo(EsQuery dto, double latitude, double longitude) throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.from(dto.getFrom());
        builder.size(dto.getSize());
        builder
            // 查询条件
            .query(QueryBuilders.geoDistanceQuery("location")
                .point(new GeoPoint(latitude, longitude))
                .distance(50, DistanceUnit.KILOMETERS)
            )
            //对结果的排序方式
            .sort(SortBuilders
                .geoDistanceSort("location", new GeoPoint(latitude, longitude))
                .order(SortOrder.ASC)
                .unit(DistanceUnit.KILOMETERS)
            );
        //显示的信息包括距离
        SearchResponse response = esClientUtils.search(dto.getIndexName(), builder);
        for (int i = 0; i < response.getHits().getHits().length; i++) {
            SearchHit hit = response.getHits().getHits()[i];
            StoreDO store = JSONObject.parseObject(hit.getSourceAsString(), StoreDO.class);
            log.info("-----" + JSONObject.toJSONString(store));
        }
        return response;
    }
}
